package com.leyou.order.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.auth.entity.UserInfo;
import com.leyou.client.GoodsClient;
import com.leyou.client.UserClient;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.Sku;
import com.leyou.order.interceptor.LoginInterceptor;
import com.leyou.order.mapper.OrderDetailMapper;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.mapper.OrderStatusMapper;
import com.leyou.order.pojo.*;
import com.leyou.user.pojo.Address;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class OrderService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private OrderStatusMapper statusMapper;

    @Autowired
    private UserClient userClient;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private GoodsClient goodsClient;

    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);

    @Transactional
    public Long createOrder(Order order) {
        // 生成orderId
        long orderId = idWorker.nextId();
        // 获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        // 初始化数据
        order.setBuyerNick(user.getUsername());
        order.setBuyerRate(false);
        order.setCreateTime(new Date());
        order.setOrderId(orderId);
        order.setUserId(user.getId());
        // 保存数据
        //this.orderMapper.insertSelective(order);
        //计算价格
        List<OrderDetail> details = order.getOrderDetails();
        int totalPrice = 0;
        String skuId = "";
        try {
            //处理orderDetail信息
            for (OrderDetail detail : details) {
                skuId += detail.getSkuId()+" ";
                Sku sku = goodsClient.querySkuById(detail.getSkuId());
                totalPrice += sku.getPrice() * detail.getNum();
                detail.setOrderId(orderId);
                String images = sku.getImages();
                String[] split = images.split(",");
                detail.setImage(split[0]);
                detail.setTitle(sku.getTitle());
                detail.setPrice(sku.getPrice());
                detail.setOwnSpec(sku.getOwnSpec());
                Integer integer = this.goodsClient.reduceStock(detail.getSkuId(), detail.getNum().longValue());
                System.out.println(integer);
                if(integer<0){
                    int a = 1/0;
                }
            }
        }catch (Exception e){
            throw new RuntimeException("下单失败,商品库存不足");
        }
        this.detailMapper.insertList(details);
        totalPrice+=Integer.parseInt(order.getPostFee());
        order.setTotalPay(Long.parseLong(totalPrice+""));
        order.setActualPay(Long.parseLong(totalPrice+""));

        //保存收货人信息
        Address address = new Address();
        Address addr = this.userClient.queryAddressById(order.getSelectedAddress());
        order.setReceiverAddress(addr.getAd());
        order.setReceiver(addr.getUname());
        order.setReceiverCity(addr.getCity());
        order.setReceiverDistrict(addr.getUarea());
        order.setReceiverState(addr.getProvince());
        order.setReceiverMobile(addr.getPhone()+"");
        order.setReceiverZip("201901");
        order.setShippingName("乐宝物流");
        order.setShippingCode("LB"+System.currentTimeMillis()+order.getUserId());
        System.out.println(order);
        this.orderMapper.insertSelective(order);

        // 保存订单状态
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        orderStatus.setCreateTime(order.getCreateTime());
        orderStatus.setStatus(1);// 初始状态为未付款

        this.statusMapper.insertSelective(orderStatus);

        Map<String, String> map = new HashMap<>();
        map.put("skuIds",skuId);
        map.put("uid",order.getUserId()+"");
        this.amqpTemplate.convertAndSend("leyou.cart.exchange","cart.delete.cart",map);

        logger.debug("生成订单，订单编号：{}，用户id：{}", orderId, user.getId());

        return orderId;
    }

    public Order queryById(Long id) {
        // 查询订单
        Order order = this.orderMapper.selectByPrimaryKey(id);

        // 查询订单详情
        OrderDetail detail = new OrderDetail();
        detail.setOrderId(id);
        List<OrderDetail> details = this.detailMapper.select(detail);
        order.setOrderDetails(details);

        // 查询订单状态
        OrderStatus status = this.statusMapper.selectByPrimaryKey(order.getOrderId());
        order.setStatus(status.getStatus());
        return order;
    }

    public PageResult<Order> queryUserOrderList(Integer page, Integer rows, Integer status,String key) {
        try {
            // 分页
            PageHelper.startPage(page, rows);
            // 获取登录用户
            UserInfo user = LoginInterceptor.getLoginUser();
            // 创建查询条件
            Page<Order> pageInfo = (Page<Order>) this.orderMapper.queryOrderList(user.getId(), status,key);

            Long pages =  Long.valueOf(pageInfo.getPages());
            return new PageResult<>(pageInfo.getTotal(), pages,pageInfo);
        } catch (Exception e) {
            logger.error("查询订单出错", e);
            return null;
        }
    }

    @Transactional
    public Boolean updateStatus(Long id, Integer status) {
        OrderStatus record = new OrderStatus();
        record.setOrderId(id);
        record.setStatus(status);
        // 根据状态判断要修改的时间
        switch (status) {
            case 2:
                record.setPaymentTime(new Date());// 付款
                break;
            case 3:
                record.setConsignTime(new Date());// 发货
                break;
            case 4:
                record.setEndTime(new Date());// 确认收获，订单结束
                break;
            case 5:
                record.setCloseTime(new Date());// 交易失败，订单关闭
                break;
            case 6:
                record.setCommentTime(new Date());// 评价时间
                break;
            default:
                return null;
        }
        int count = this.statusMapper.updateByPrimaryKeySelective(record);
        return count == 1;
    }


    /**
     * 后台管理用查询所有订单
     * @return
     */
    public List<OrderStatus> queryOrders() {
        List<OrderStatus> orderStatuses = statusMapper.selectAll();
        orderStatuses.forEach(orderStatus -> {
            Order order = orderMapper.selectByPrimaryKey(orderStatus.getOrderId());
            orderStatus.setActualPay(order.getActualPay());
        });
        return orderStatuses;
    }

    public List<OrderDetail> queryOrderDetailsByOrderId(Long id) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(id);
        List<OrderDetail> detailList = detailMapper.select(orderDetail);
        return detailList;
    }


    public List<Transaction> queryTransaction() {
        //开始分页
        //PageHelper.startPage(page,rows);

        //查询所有订单详情
        List<OrderDetail> orderDetails = this.detailMapper.selectAll();
        //定义一个集合存skuId
        List<Long> skuIds=new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            if (!skuIds.contains(orderDetail.getSkuId())){
                skuIds.add(orderDetail.getSkuId());
            }
        }
        //定义一个结合存放交易详情
        List<Transaction> list = new ArrayList<>();
        List<Sku> skus = new ArrayList<>();
        for (Long skuId : skuIds) {
            Transaction transaction = new Transaction();
            Sku sku = this.goodsClient.querySkuById(skuId);
            int num = 0;
            for (OrderDetail orderDetail : orderDetails) {
                if (orderDetail.getSkuId()==skuId){
                    num = num + orderDetail.getNum();
                }
            }

            //赋值
            BeanUtils.copyProperties(sku,transaction);
            transaction.setNum(num);
            list.add(transaction);
            skus.add(sku);
        }

        // PageInfo<Transaction> pageInfo = new PageInfo<>(list);

        return list;
    }



}
